package com.ustc.hewei.nettyrpc2_0.netty.client.loadBalance.impl;

import com.google.common.hash.Hashing;
import com.ustc.hewei.nettyrpc2_0.common.warp.ZkNode;
import com.ustc.hewei.nettyrpc2_0.netty.client.loadBalance.CommonLoadBalance;

import java.util.ArrayList;
import java.util.List;

/**
* @description: 一致性哈希负载均衡
* @author hewei
* @date 2022/9/8 14:17
* @version 1.0
*/

public class ConsistentHash implements CommonLoadBalance {
    @Override
    public ZkNode getService(List<ZkNode> zkNodeList) {
        if (zkNodeList == null || zkNodeList.size() <= 0) {
            return null;
        }
        List<ZkNode> goodNodeList = new ArrayList<>();
        for (ZkNode zkNode : zkNodeList) {
            int weight = zkNode.getWeight();
            if (weight <= 0) continue;
            goodNodeList.add(zkNode);
        }
        if (goodNodeList.size() == 0) return null;
        int index = Hashing.consistentHash(zkNodeList.get(0).getServiceName().hashCode(), goodNodeList.size());
        return goodNodeList.get(index);
    }
}
